package com.atguigu.day04;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Felix
 * @date 2024/7/12
 * 该案例演示通过connect实现innerjoin的效果
 * 需求：连接两条流，输出能根据id匹配上的数据（类似inner join效果）
 */
public class Flink07_connect_inner_join {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        Configuration conf = new Configuration();
        conf.set(RestOptions.PORT,8088);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        //TODO 2.准备2条流
        DataStreamSource<Tuple2<Integer, String>> source1 = env.fromElements(
                Tuple2.of(1, "a1"),
                Tuple2.of(1, "a2"),
                Tuple2.of(2, "b"),
                Tuple2.of(3, "c")
        );
        DataStreamSource<Tuple3<Integer, String, Integer>> source2 = env.fromElements(
                Tuple3.of(1, "aa1", 1),
                Tuple3.of(1, "aa2", 2),
                Tuple3.of(2, "bb", 1),
                Tuple3.of(3, "cc", 1)
        );
        //TODO 3.连接两条流
        ConnectedStreams<Tuple2<Integer, String>, Tuple3<Integer, String, Integer>> connectDS = source1.connect(source2);

        //TODO 4.按照id进行分组---指定2条流的连接条件
        ConnectedStreams<Tuple2<Integer, String>, Tuple3<Integer, String, Integer>> keyedDS = connectDS.keyBy(
                tup2 -> tup2.f0,
                tup3 -> tup3.f0
        );
        
        //TODO 5.对流中数据进行处理
        SingleOutputStreamOperator<String> processDS = keyedDS.process(
                new CoProcessFunction<Tuple2<Integer, String>, Tuple3<Integer, String, Integer>, String>() {
                    private Map<Integer, List<Tuple2<Integer, String>>> ds1Cache = new HashMap<>();
                    private Map<Integer, List<Tuple3<Integer, String, Integer>>> ds2Cache = new HashMap<>();

                    //处理第一条数据
                    @Override
                    public void processElement1(Tuple2<Integer, String> tup2, CoProcessFunction<Tuple2<Integer, String>, Tuple3<Integer, String, Integer>, String>.Context ctx, Collector<String> out) throws Exception {
                        //获取id
                        Integer id = tup2.f0;
                        //将当前数据放到缓存中缓存起来
                        if (ds1Cache.containsKey(id)) {
                            ds1Cache.get(id).add(tup2);
                        } else {
                            List<Tuple2<Integer, String>> ds1List = new ArrayList<>();
                            ds1List.add(tup2);
                            ds1Cache.put(id, ds1List);
                        }
                        //用当前这条数据和另外一条流中已经缓存的数据进行关联
                        if (ds2Cache.containsKey(id)) {
                            for (Tuple3<Integer, String, Integer> tup3 : ds2Cache.get(id)) {
                                out.collect(tup2 + "---" + tup3);
                            }
                        }
                    }

                    //处理第二条数据
                    @Override
                    public void processElement2(Tuple3<Integer, String, Integer> tup3, CoProcessFunction<Tuple2<Integer, String>, Tuple3<Integer, String, Integer>, String>.Context ctx, Collector<String> out) throws Exception {
                        Integer id = tup3.f0;
                        if (ds2Cache.containsKey(id)) {
                            ds2Cache.get(id).add(tup3);
                        } else {
                            List<Tuple3<Integer, String, Integer>> ds2List = new ArrayList<>();
                            ds2List.add(tup3);
                            ds2Cache.put(id, ds2List);
                        }
                        //用当前这条数据  和另外一条流中已经缓存的数据进行关联(另一条流先来了)
                        if (ds1Cache.containsKey(id)) {
                            for (Tuple2<Integer, String> tup2 : ds1Cache.get(id)) {
                                out.collect(tup2 + "---" + tup3);
                            }
                        }
                    }
                }
        );

        //TODO 6.打印输出
        processDS.print();

        //TODO 7.提交作业
        env.execute();


    }
}
